/**
 * (c) Copyright Ascensio System SIA 2025
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hulman.oms.office.controller;

import com.hulman.oms.bean.Result;
import com.hulman.oms.util.FileUtil;
import com.hulman.oms.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/office")
@Slf4j
public class FileController
{
    @Value("${file-home}")
    private String fileHome;
    @Autowired
    private HttpServletResponse response;

    @GetMapping("/download/{fileId}")
    public void download(@PathVariable String fileId, String fileName) throws Exception
    {
        log.info("onlyoffice download file: {}", fileId);
        InputStream in = Files.newInputStream(new File(fileHome + fileId).toPath());
        response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode(fileId, "UTF-8"));
        OutputStream os = response.getOutputStream();
        if (!StringUtil.isEmpty(fileName))
        {
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        }
        byte[] b = new byte[1024];
        int length;
        while ((length = in.read(b)) > 0)
        {
            os.write(b, 0, length);
        }
        os.close();
        in.close();
    }

    /**
     * 上传文件
     *
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception
    {
        Map<String, Object> data = new HashMap<>();
        String fileName = file.getOriginalFilename();
        String ext = FileUtil.parseExtName(fileName);
        String uuid = StringUtil.uuid();
        String storageName = "tmp_" + uuid + "." + ext;
        File fileToUpload = new File(fileHome + storageName);
        file.transferTo(fileToUpload);
        data.put("storageName", storageName);
        data.put("fileName", fileName);
        return new Result(data);
    }
}
